#!/usr/bin/env python3
"""
Rules Integration Engine - Intelligent Rules V2 Coordination
实现NB项目rules与intelligent_rules_v2的无缝集成
"""

import os
import yaml
from typing import Dict, Any, List, Optional, Set
from pathlib import Path
import logging

logger = logging.getLogger(__name__)

class RulesIntegrationEngine:
    """
    Rules集成引擎 - 实现双层rules的无缝集成
    
    架构：
    - Level 1: intelligent_rules_v2/rules/ (通用底座rules)
    - Level 2: NB_project/rules/ (项目专属rules)
    """
    
    def __init__(self, project_root: str = None):
        self.project_root = Path(project_root) if project_root else Path.cwd()
        
        # 通用底座rules路径
        self.foundation_rules_dir = self.project_root / "rules"
        
        # 项目专属rules路径 (父目录的rules)
        self.project_rules_dir = self.project_root.parent / "rules"
        
        # 集成后的rules缓存
        self.integrated_rules = {}
        self.rules_hierarchy = {}
        
        # 冲突解决策略
        self.conflict_resolution_strategy = "project_priority"  # 项目规则优先
        
        logger.info(f"✅ Rules Integration Engine initialized")
    
    def discover_rules_structure(self) -> Dict[str, Any]:
        """发现rules结构"""
        structure = {
            "foundation_rules": self._scan_rules_directory(self.foundation_rules_dir),
            "project_rules": self._scan_rules_directory(self.project_rules_dir),
            "integration_needed": False
        }
        
        # 检查是否需要集成
        if structure["foundation_rules"]["total"] > 0 and structure["project_rules"]["total"] > 0:
            structure["integration_needed"] = True
            logger.info("🔄 Rules integration needed")
        
        return structure
    
    def _scan_rules_directory(self, rules_dir: Path) -> Dict[str, Any]:
        """扫描rules目录"""
        if not rules_dir.exists():
            return {"total": 0, "categories": {}, "files": []}
        
        categories = {}
        files = []
        
        for category in ["core", "system", "evolution", "validation"]:
            category_dir = rules_dir / category
            if category_dir.exists():
                rule_files = list(category_dir.glob("*.yaml"))
                categories[category] = len(rule_files)
                files.extend([str(f) for f in rule_files])
        
        return {
            "total": len(files),
            "categories": categories,
            "files": files,
            "directory": str(rules_dir)
        }
    
    def integrate_rules(self) -> Dict[str, Any]:
        """
        集成双层rules
        
        集成策略：
        1. 加载foundation rules (通用底座)
        2. 加载project rules (项目专属)
        3. 智能合并，解决冲突
        4. 建立rules层次结构
        """
        integration_result = {
            "success": False,
            "integrated_rules_count": 0,
            "conflicts_resolved": 0,
            "hierarchy_levels": 0,
            "errors": []
        }
        
        try:
            # 加载foundation rules
            foundation_rules = self._load_rules_from_directory(self.foundation_rules_dir, "foundation")
            
            # 加载project rules  
            project_rules = self._load_rules_from_directory(self.project_rules_dir, "project")
            
            # 智能合并rules
            merged_rules, conflicts = self._merge_rules_intelligently(foundation_rules, project_rules)
            
            # 建立层次结构
            hierarchy = self._build_rules_hierarchy(merged_rules)
            
            # 更新缓存
            self.integrated_rules = merged_rules
            self.rules_hierarchy = hierarchy
            
            integration_result.update({
                "success": True,
                "integrated_rules_count": len(merged_rules),
                "conflicts_resolved": len(conflicts),
                "hierarchy_levels": len(hierarchy),
                "foundation_rules": len(foundation_rules),
                "project_rules": len(project_rules)
            })
            
            logger.info(f"✅ Rules integration completed: {len(merged_rules)} rules integrated")
            
        except Exception as e:
            integration_result["errors"].append(str(e))
            logger.error(f"❌ Rules integration failed: {e}")
        
        return integration_result
    
    def _load_rules_from_directory(self, rules_dir: Path, source: str) -> Dict[str, Any]:
        """从目录加载rules"""
        rules = {}
        
        if not rules_dir.exists():
            return rules
        
        for category in ["core", "system", "evolution", "validation"]:
            category_dir = rules_dir / category
            if category_dir.exists():
                for rule_file in category_dir.glob("*.yaml"):
                    try:
                        with open(rule_file, "r", encoding="utf-8") as f:
                            rule_content = yaml.safe_load(f)
                        
                        rule_name = rule_file.stem
                        rules[rule_name] = {
                            "source": source,
                            "category": category,
                            "content": rule_content,
                            "file_path": str(rule_file)
                        }
                        
                    except Exception as e:
                        logger.error(f"❌ Failed to load rule {rule_file}: {e}")
        
        return rules
    
    def _merge_rules_intelligently(self, foundation_rules: Dict[str, Any], project_rules: Dict[str, Any]) -> tuple:
        """智能合并rules"""
        merged_rules = foundation_rules.copy()
        conflicts = []
        
        for rule_name, project_rule in project_rules.items():
            if rule_name in merged_rules:
                # 发现冲突
                conflict = {
                    "rule_name": rule_name,
                    "foundation_source": merged_rules[rule_name]["file_path"],
                    "project_source": project_rule["file_path"],
                    "resolution": self.conflict_resolution_strategy
                }
                
                # 应用冲突解决策略
                if self.conflict_resolution_strategy == "project_priority":
                    # 项目rules优先
                    merged_rules[rule_name] = project_rule
                    merged_rules[rule_name]["override_source"] = "project"
                elif self.conflict_resolution_strategy == "foundation_priority":
                    # 保持foundation rules
                    merged_rules[rule_name]["override_source"] = "foundation"
                elif self.conflict_resolution_strategy == "merge":
                    # 智能合并内容
                    merged_rules[rule_name] = self._merge_rule_content(merged_rules[rule_name], project_rule)
                
                conflicts.append(conflict)
            else:
                # 无冲突，直接添加
                merged_rules[rule_name] = project_rule
        
        return merged_rules, conflicts
    
    def _merge_rule_content(self, foundation_rule: Dict[str, Any], project_rule: Dict[str, Any]) -> Dict[str, Any]:
        """合并rule内容"""
        # 简化版合并策略 - 项目规则补充foundation规则
        merged_rule = foundation_rule.copy()
        
        # 合并content
        foundation_content = foundation_rule.get("content", {})
        project_content = project_rule.get("content", {})
        
        # 深度合并
        merged_content = self._deep_merge_dict(foundation_content, project_content)
        merged_rule["content"] = merged_content
        merged_rule["merged_from"] = ["foundation", "project"]
        
        return merged_rule
    
    def _deep_merge_dict(self, base: Dict[str, Any], overlay: Dict[str, Any]) -> Dict[str, Any]:
        """深度合并字典"""
        result = base.copy()
        
        for key, value in overlay.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._deep_merge_dict(result[key], value)
            else:
                result[key] = value
        
        return result
    
    def _build_rules_hierarchy(self, rules: Dict[str, Any]) -> Dict[str, Any]:
        """建立rules层次结构"""
        hierarchy = {
            "foundation_layer": {},
            "project_layer": {},
            "merged_layer": {},
            "categories": {"core": [], "system": [], "evolution": [], "validation": []}
        }
        
        for rule_name, rule_data in rules.items():
            source = rule_data.get("source", "unknown")
            category = rule_data.get("category", "unknown")
            
            # 按source分层
            if source == "foundation":
                hierarchy["foundation_layer"][rule_name] = rule_data
            elif source == "project":
                hierarchy["project_layer"][rule_name] = rule_data
            
            # 按category分类
            if category in hierarchy["categories"]:
                hierarchy["categories"][category].append(rule_name)
            
            # 如果是合并的rule
            if "merged_from" in rule_data:
                hierarchy["merged_layer"][rule_name] = rule_data
        
        return hierarchy
    
    def get_rule_by_name(self, rule_name: str) -> Optional[Dict[str, Any]]:
        """根据名称获取rule"""
        return self.integrated_rules.get(rule_name)
    
    def get_rules_by_category(self, category: str) -> List[Dict[str, Any]]:
        """根据类别获取rules"""
        if category not in self.rules_hierarchy.get("categories", {}):
            return []
        
        rule_names = self.rules_hierarchy["categories"][category]
        return [self.integrated_rules[name] for name in rule_names if name in self.integrated_rules]
    
    def get_integration_status(self) -> Dict[str, Any]:
        """获取集成状态"""
        return {
            "integrated_rules_count": len(self.integrated_rules),
            "hierarchy_levels": len(self.rules_hierarchy),
            "foundation_rules_path": str(self.foundation_rules_dir),
            "project_rules_path": str(self.project_rules_dir),
            "conflict_resolution_strategy": self.conflict_resolution_strategy,
            "version": "2.0.0"
        }

# 全局集成引擎实例
_global_integration_engine = None

def get_integration_engine() -> RulesIntegrationEngine:
    """获取全局集成引擎实例"""
    global _global_integration_engine
    if _global_integration_engine is None:
        _global_integration_engine = RulesIntegrationEngine()
    return _global_integration_engine

if __name__ == "__main__":
    print("🧪 Testing Rules Integration Engine V2...")
    engine = RulesIntegrationEngine()
    
    # 发现rules结构
    structure = engine.discover_rules_structure()
    print(f"📋 Rules structure: {structure}")
    
    # 集成rules
    result = engine.integrate_rules()
    print(f"✅ Integration result: {result}")
    
    print("🎉 Rules Integration Engine V2 test completed!")

